<template>
    <el-card class="box-card" shadow="hover">
        <template #header>
            <el-button @click="addtrademark" type="primary" :icon="Plus"  v-visite="'btn.Trademark.add'">添加</el-button>
        </template>
        <el-table style="width: 100%" border :data="tmObj.records" v-loading="loading" element-loading-text="努力加载中..."
            element-loading-background="rgba(122, 122, 122, 0.2)">
            <el-table-column align="center" label="序号" width="80" type='index' />
            <el-table-column label="品牌名称" prop="tmName" />
            <el-table-column label="品牌LOG">
                <template #="{row,$index}">
                    <a :title="row.tmName"></a>
                    <img :src="row.logoUrl" style="width: 100px; height: 60px; border-radius: 10px">
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #="{ row, $index }">
                    <el-button type="warning" size="small" :icon="Edit" @click="UpdataTrademark(row)"></el-button>

                    <el-popconfirm :title="`你确定要删除${row.tmName}吗?`" @confirm="deltrademark(row)">
                        <template #reference>
                            <el-button type="danger" size="small" :icon="Delete"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" background :page-sizes="[3,5,7]"
            :total="tmObj.total" :pager-count="7" style="margin-top:20px"
            layout=" prev, pager, next,jumper,->,sizes,total" @current-change="geTrademarkList"
            @size-change="sizeHander"></el-pagination>


        <!--对话框:添加新的品牌、或者修改已有品牌时候会用到
        v-model:控制对话框显示与隐藏
    -->
        <el-dialog v-model="dialogFormVisible" title="添加品牌" draggable>
            <el-form style="width:80%" label-width="90px" :model="tmParams" :rules="rules" ref="formRef">
                <!--收集品牌名称地方-->
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input autocomplete="off" v-model="tmParams.tmName" />
                </el-form-item>
                <!--收集品牌 lOGO地方-->
                <el-form-item label="品牌LOGO" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/app-dev/admin/product/fileUpload"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="tmParams.logoUrl" :src="tmParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrUpdate">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts">
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus
} from '@element-plus/icons-vue'
// 引入消息提示框
import { ElMessage } from 'element-plus'
//引入上传图片成功人家需要的类型
import type { UploadProps, FormInstance, FormRules } from "element-plus";

//引入接口
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqtrademarklist, reqAddOrUpdateTradeMark, reqDeleteTrademark } from '@/api/product/trademark/trademark'
// console.log(reqtrademarklist)
// 引入数据类型
import type { trademarkResponseData, trademark } from '@/api/product/trademark/model/trademark'
let currentPage = ref<number>(1)//页码数
let pageSize = ref<number>(3)//每页条数

// 控制dialog对话框显示与隐藏
let dialogFormVisible = ref<boolean>(false)

//定义控制loding效果响应式数据
let loading = ref<boolean>(false);

const formRef = ref<FormInstance>()

// 添加商品收集的数据
let tmParams = reactive<trademark>({
    tmName: '',
    logoUrl: ''
})
// 商品返回的数据
let tmObj = reactive<trademarkResponseData>({
    total: 0,
    records: []
})
//组件挂载完毕需要先获取一次品牌数据:第一页、三条数据
onMounted(() => {
    // 获取一次品牌数据
    geTrademarkList(1)
})

const geTrademarkList = async (page: number = 1) => {
    //发请求之前loading加载
    loading.value = true;
    // 整理参数
    currentPage.value = page;
    // 发送请求
    let result = await reqtrademarklist(currentPage.value, pageSize.value)
    tmObj.total = result.total  //数据总条数
    tmObj.records = result.records //品牌数据
    // console.log(result);
    //发请求之前loading加载
    loading.value = false;
}

// 右边下拉菜单修改一页展示几条数据的回调
const sizeHander = (limit: number) => {
    // 整理参数
    pageSize.value = limit;
    // 发送请求
    geTrademarkList();
}
// 添加按钮
const addtrademark = () => {
    dialogFormVisible.value = true
    // 清空内容
    tmParams.tmName = ''
    tmParams.logoUrl = ''
    tmParams.id = ''

    //nextTick:当响应式数据发生变化(页面重新渲染),获取更新后的DOM
    nextTick(() => {
        formRef.value?.resetFields()
    });
}

//上传图片成功的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    // console.log(response);
    //response:上传图片成功服务器返回数据
    //图片学校远程服务器地址
    tmParams.logoUrl = response.data;
};

//图片上传成功之前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
    //图片相关的信息
    //外层约束类型
    if (
        rawFile.type == "image/jpeg" ||
        rawFile.type == "image/png" ||
        rawFile.type == "image/gif"
    ) {
        //约束大小1024B->1K->1M->1G->1T
        if (rawFile.size / 1024 / 1024 <= 5) {
            return true;
        }
    } else {
        return false;
    }
};

// 点击上传数据按钮
const addOrUpdate = async () => {
    formRef.value?.validate(async (success) => {
        if (success) {
            // 发送给请求
            await reqAddOrUpdateTradeMark(tmParams)
            // 关闭添加框
            dialogFormVisible.value = false

            // 更新页面
            geTrademarkList(tmParams.id ? currentPage.value : 1)
            // 消息提示框
            ElMessage({
                message: tmParams.id ? '修改成功' : '添加成功',
                type: 'success',
            })
        } else {
            ElMessage({
                message: '请阅读上传规则',
                type: 'error',
            })

        }

    })
}

// 修改按钮
const UpdataTrademark = async (row: trademark) => {
    dialogFormVisible.value = true

   
    nextTick(() => {
        
        formRef.value?.resetFields()
        // 收集数据
        tmParams.id = row.id
        tmParams.tmName = row.tmName
        tmParams.logoUrl = row.logoUrl
    });
}

// 表单验证
const rules = reactive<FormRules>({
    tmName: [
        { required: true, message: '亲爱的品牌名字不能为空', trigger: 'blur' },
        { required: true, min: 2, max: 10, message: '请输入2-10之间的名字', trigger: 'blur' },
    ],
    logoUrl: [
        { required: true, message: '请你上传logo图片' },
    ]
})

// 删除商品
const deltrademark = async (row: any) => {
    try {
        await reqDeleteTrademark(row.id)
        geTrademarkList(currentPage.value)
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
    } catch (error) {
        ElMessage({
            message: '删除失败',
            type: 'error',
        })
    }
}

</script>

<style scoped>
/**上传照片的样式**/
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>